/**
*  
* @Function 数据催收Controller 
* @ProjectName credit-data-platform 
* @PackageName com.py.credit.controller    
* @FileName TaskRemindController.java    
* @Date 2018年5月9日上午10:37:15
* @Author Min DongXv
* @Copyright (c) 2018, 金电联行 All Rights Reserved.   
*   
*/
package com.py.credit.controller;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.TaskRemindFieldEnum;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.TaskRemindService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * 
 * @Function 数据催收Controller
 * @ClassName TaskRemindController
 * @Date 2018年5月9日 上午10:37:15
 * @Author Min DongXv
 * 
 */
@RestController
@RequestMapping(value = "/taskRemind")
public class TaskRemindController extends BaseController {

	private final static String TASK_REMIND_ID = "task_remind";

	private final static String DATA_REMIND_ID = "data_remind";

	private final static String TYPE_C = "C";

	@Autowired
	private TaskRemindService taskRemindService;

	@Autowired
	private RemoteBaseService remoteBaseService;

	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		return new RestServiceResult<List<OptionalColumn>>(TaskRemindFieldEnum.getOptionalColumns());

	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		return new RestServiceResult<List<OptionalColumn>>(TaskRemindFieldEnum.getAdvancedConditionColumns());
	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			@RequestParam(value = "type", defaultValue = "T", required = true) String type,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("TaskRemindController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String column = StringUtils.join(columns, ",");
		column = column + ",id" + ",subscriptionRegionId" + ",subscriberId";
		if (StringUtils.isNotBlank(type) && TYPE_C.equals(type)) {
			// 数据催收
			MapCache.set(userInfo.getId() + "_" + DATA_REMIND_ID, StringUtils.split(column, ","));
		} else {
			// 任务提醒
			MapCache.set(userInfo.getId() + "_" + TASK_REMIND_ID, StringUtils.split(column, ","));
		}
		return new RestServiceResult<String>();
	}

	/**
	 * 
	 * @api {get} /taskRemind/getTaskRemindList.json 分页查询数据催收信息
	 * @apiName getTaskRemindList
	 * @apiVersion 0.0.1
	 * @apiGroup 数据催收
	 * @apiParam {String} type 类型 C:数据催收 T:任务提醒
	 * @apiParamExample {json} 请求参数示例 {"type":"C"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} infoVersion 版本名称
	 * @apiSuccess {String} infoName 订阅目录名称
	 * @apiSuccess {String} subscriberName 订阅人
	 * @apiSuccess {String} subscriptionRegion 订阅区县
	 * @apiSuccess {String} remindTime 催收时间
	 * @apiSuccess {String} dataStatus 订阅状态
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"infoVersion":"版本v_1.0","infoName":"12","subscriberName":"超级管理员","subscriptionRegion":1,"remindTime":1525845094000,"dataStatus":"W"}]}
	 */
	@RequestMapping(value = "/getTaskRemindList.json")
	public RestServiceResult<List<Map<String, Object>>> getTaskRemindList(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			@RequestParam(value = "type", defaultValue = "T", required = true) String type,
			HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("TaskRemindController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] configColumns = null;
		// 数据催收
		if (StringUtils.isNotBlank(type) && TYPE_C.equals(type)) {
			configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + DATA_REMIND_ID);
		} else {
			// 任务提醒
			configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + TASK_REMIND_ID);
		}
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? TaskRemindFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		try {
			List<Map<String, Object>> data = taskRemindService.selectTaskRemindByConditionForPage(showColumns, null,
					condition, page, type, userInfo);
			// 调用用户远程服务，进行姓名填充
			Set<Integer> userIds = new HashSet<Integer>();
			for (Map<String, Object> map : data) {
				if (null != map) {
					if (null != map.get("subscriberId")) {
						userIds.add(Integer.parseInt(String.valueOf(map.get("subscriberId"))));
					}
				}
			}
			data = remoteBaseService.matchUserName(data, result, HttpServletHelper.getUserToken(request), userIds,
					"subscriberId", "subscriberName");
			if (RestServiceResult.CODE_SUCCESS != result.getCode()) {
				return result;
			}
			result.setData(data);
			result.setCount(page.getTotalCount());
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("查询数据催收信息异常，请稍后再试！");
			ExceptionLogger.error("分页查询数据催收信息异常！", e.getMessage(), e);
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /taskRemind/export.json 任务提醒和数据催收导出
	 * @apiName exportData
	 * @apiVersion 0.0.1
	 * @apiGroup 数据催收
	 * @apiParam {String} condition
	 * @apiParam {String} showColumn 导出列编码的数组
	 * @apiParam {type} type 类型 C:数据催收 T:任务提醒
	 * @apiParamExample {json} 请求参数示例
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果
	 */
	@RequestMapping(value = "/export")
	public RestServiceResult<List<Map<String, Object>>> exportData(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
			HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "type", defaultValue = "T", required = true) String type) {
		page.setLimit(1000);
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("TaskRemindController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		showColumns.add("id");
		showColumns.add("subscriptionRegionId");
		showColumns.add("subscriberId");
		List<Map<String, Object>> data;
		try {
			data = taskRemindService.selectTaskRemindByConditionForPage(showColumns, null, condition, page, type,
					userInfo);
			// 调用用户远程服务，进行姓名填充
			Set<Integer> userIds = new HashSet<Integer>();
			for (Map<String, Object> map : data) {
				if (null != map) {
					if (null != map.get("subscriberId")) {
						userIds.add(Integer.parseInt(String.valueOf(map.get("subscriberId"))));
					}
				}
			}
			data = remoteBaseService.matchUserName(data, result, HttpServletHelper.getUserToken(request), userIds,
					"subscriberId", "subscriberName");
			if (RestServiceResult.CODE_SUCCESS != result.getCode()) {
				return result;
			}
			String title = "任务提醒";
			if (StringUtils.isNotBlank(type) && TYPE_C.equals(type)) {
				title = "数据催收";
			}
			ExcelUtil.downloadExcel(response, data, title, title, showColumns,
					TaskRemindFieldEnum.getOptionalColumns());
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("归集部门绩效统计导出异常，请稍后再试！");
			ExceptionLogger.error("归集部门绩效统计导出异常！", e.getMessage(), e);
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /taskRemind/updateTaskRemind.json 更新任务提醒和数据催收状态
	 * @apiName updateTaskRemind
	 * @apiVersion 0.0.1
	 * @apiGroup 数据催收
	 * @apiParam {string} status 数据状态 Y:已读 W:未读
	 * @apiParam {int} id
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/updateRemind")
	public RestServiceResult<Object> updateRemind(
			@RequestParam(value = "status", required = true, defaultValue = "Y") String status,
			@RequestParam(value = "id", required = true) Integer id) {
		taskRemindService.updateTaskRemind(id, status);
		return new RestServiceResult<>();
	}
}
